package com.chookss.view

import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ListAdapter
import android.widget.ListView

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2021/1/20 14:32
 * Note:
 */
open class BottomListDialog(context: Context,title:String):BottomDialog(context,title) {
    val mListView by lazy {
        createListView()
    }
    var listener: DialogInterface.OnClickListener? = null
    var indexPosition: Int = 0

    override fun createContentView() = mListView

    open fun createListView():ListView {
        var listView = DialogListView(context)
        listView.cacheColorHint =Color.parseColor("#00000000")
        listView.setBackgroundColor(Color.parseColor("#00000000"))
        listView.maxHeight =  (screenSizeInPixel(context).y * 0.6f).toInt()
        listView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        listView!!.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            dismiss()
            if (listener != null) {
                indexPosition=position
                listener!!.onClick(this@BottomListDialog, position)
            }
        }

        return listView
    }


    fun setItems(adapter: ListAdapter?,indexPosition:Int, listener: DialogInterface.OnClickListener?): BottomListDialog? {
        this.listener = listener
        mListView!!.adapter = adapter
//        setTitle("测试")
        if(indexPosition<=2){
        }else if(indexPosition+3<mListView!!.adapter.count){
            mListView.post(Runnable { mListView.smoothScrollToPosition(indexPosition+3) })
        }else{
            mListView.post(Runnable { mListView.smoothScrollToPosition(mListView!!.adapter.count-1) })
        }
        return this
    }
    fun setTitles(text: String?) {
         setTitle(text)
    }
    fun showDialog() {
        mListView.post(Runnable { mListView.smoothScrollToPosition(indexPosition) })
        show()
    }
    class DialogListView(context: Context?) : ListView(context) {
        var maxHeight = 0
        override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST))
        }
    }
}